import requests
from bs4 import BeautifulSoup


def get_weather_by_bing(query):
    # 构造百度搜索的URL
    search_url = f"https://www.baidu.com/s?wd={query}"

    # 构造请求头，模拟浏览器访问
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    }

    # 发送请求
    response = requests.get(search_url, headers=headers)
    print(response.text)
    # 检查请求是否成功
    if response.status_code == 200:
        # 使用BeautifulSoup解析HTML内容
        soup = BeautifulSoup(response.text, 'html.parser')

        # 搜索包含天气信息的元素，这里需要根据实际页面结构来定位
        # 以下代码仅为示例，可能需要根据实际情况调整
        weather_info = soup.find('div', {'class': 'c_weather'})

        if weather_info:
            # 提取天气信息
            current_temp = weather_info.find('span', {'class': 'weather-main-temp_6CEpK'})
            return current_temp.text if current_temp else '未找到天气信息'
        else:
            return '未找到天气信息'
    else:
        return '请求失败，状态码：' + str(response.status_code)


# 使用函数查询天气
query = "上海天气"
print(get_weather_by_bing(query))